export const animationDirective = {
  mounted(el, binding) {
    const defaultOptions = {
      type: 'fade', // 默认动画类型
      duration: 800, // 默认动画时长
      delay: 0, // 默认延迟
      easing: 'ease-out' // 默认缓动函数
    }

    const options = { ...defaultOptions, ...binding.value }

    // 根据动画类型设置不同的动画效果
    const animationStyles = {
      fade: [
        { opacity: 0, transform: 'translateY(20px)' },
        { opacity: 1, transform: 'translateY(0)' }
      ],
      scale: [
        { opacity: 0, transform: 'scale(0.8)' },
        { opacity: 1, transform: 'scale(1)' }
      ],
      slide: [
        { opacity: 0, transform: 'translateX(-50px)' },
        { opacity: 1, transform: 'translateX(0)' }
      ]
    }

    const keyframes = animationStyles[options.type] || animationStyles.fade

    el.style.opacity = '0'
    el.style.transform = keyframes[0].transform

    // 使用 IntersectionObserver 实现滚动触发动画
    const observer = new IntersectionObserver(
      (entries) => {
        entries.forEach((entry) => {
          if (entry.isIntersecting) {
            entry.target.animate(keyframes, {
              duration: options.duration,
              delay: options.delay,
              easing: options.easing,
              fill: 'forwards'
            })
            observer.unobserve(entry.target)
          }
        })
      },
      { threshold: 0.1 }
    )

    observer.observe(el)
  }
}

export default {
  install(app) {
    app.directive('animate', animationDirective)
  }
}
